package cn.daniellee.plugin.wc.storage;

import cn.daniellee.plugin.wc.Welcome;
import cn.daniellee.plugin.wc.model.PlayerData;

import javax.swing.plaf.nimbus.State;
import java.sql.*;

public class MysqlStorage extends Storage {

	private Connection connection;

	private final String tablePrefix = Welcome.getInstance().getConfig().getString("storage.mysql.table-prefix", "wc_");

	@Override
	public boolean initialize() {
		// 初始化Mysql驱动
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while getting the Mysql database driver.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
			return false;
		}
		// 初始化连接
		String url = "jdbc:mysql://" + Welcome.getInstance().getConfig().getString("storage.mysql.host", "localhost") + ":" + Welcome.getInstance().getConfig().getInt("storage.mysql.port", 3306) + "/" + Welcome.getInstance().getConfig().getString("storage.mysql.database", "minecraft") + "?" + Welcome.getInstance().getConfig().getString("storage.mysql.parameter", "characterEncoding=utf8mb4&useSSL=false");
		try {
			connection = DriverManager.getConnection(url, Welcome.getInstance().getConfig().getString("storage.mysql.username", "username"), Welcome.getInstance().getConfig().getString("storage.mysql.password", "password"));
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]Mysql connection information is incorrect.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
			return false;
		}
		// 初始化Player表
		String playerSql = "CREATE TABLE IF NOT EXISTS `" + tablePrefix + "player` (" +
				"  `name` varchar(48) NOT NULL COMMENT 'Player Name'," +
				"  `join_date` bigint(20) DEFAULT '0' COMMENT 'Join Datetime'," +
				"  PRIMARY KEY (`name`)," +
				"  UNIQUE KEY `index_name` (`name`) USING BTREE" +
				") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";

		try(Statement statement = connection.createStatement()) {
			statement.execute(playerSql);
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while initializing the Mysql player table.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
			return false;
		}
		// 初始化Welcomed表
		String welcomedSql = "CREATE TABLE IF NOT EXISTS `" + tablePrefix + "welcomed` (" +
				"  `name` varchar(48) NOT NULL COMMENT 'Player Name'," +
				"  `welcomer` varchar(48) NOT NULL COMMENT 'Welcomer Name'," +
				"  KEY `index_name` (`name`) USING BTREE" +
				") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";
		try(Statement statement = connection.createStatement()) {
			statement.execute(welcomedSql);
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while initializing the Mysql welcomed table.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
			return false;
		}
		return true;
	}

	@Override
	public Connection getConnection() {
		return connection;
	}

	@Override
	public PlayerData getPlayerDataByName(String name) {
		PlayerData playerData = null;
		String sql = " SELECT `name`,`join_date` FROM `" + tablePrefix + "player` WHERE `name` = ?";
		try (PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, name);
			ResultSet resultSet = statement.executeQuery();
			if (resultSet.next()) {
				playerData = new PlayerData(name);
				playerData.setJoinDate(resultSet.getLong("join_date"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while reading building data from Mysql.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
		}
		return playerData;
	}

	@Override
	public void addPlayerData(PlayerData playerData) {
		String sql = "INSERT INTO `" + tablePrefix + "player` (`name`,`join_date`)VALUES(?,?)";
		try(PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, playerData.getName());
			statement.setLong(2, playerData.getJoinDate());
			statement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while writing building data to Mysql.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
		}
	}

	@Override
	public boolean checkWelcomed(String welcomee, String welcomer) {
		String sql = " SELECT `name`,`welcomer` FROM `" + tablePrefix + "welcomed` WHERE `name` = ? AND `welcomer` = ?";
		try (PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, welcomee);
			statement.setString(2, welcomer);
			ResultSet resultSet = statement.executeQuery();
			return resultSet.next();
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while reading building data from Mysql.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
		}
		// 默认返回True，避免出错时一直欢迎成功
		return true;
	}

	@Override
	public void addWelcomed(String welcomee, String welcomer) {
		String sql = "INSERT INTO `" + tablePrefix + "welcomed` (`name`,`welcomer`)VALUES(?,?)";
		try(PreparedStatement statement = connection.prepareStatement(sql)) {
			statement.setString(1, welcomee);
			statement.setString(2, welcomer);
			statement.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			Welcome.getInstance().getLogger().info(" ");
			Welcome.getInstance().getLogger().info("[Welcome]An error occurred while writing building data to Mysql.".replace("&", "§"));
			Welcome.getInstance().getLogger().info(" ");
		}
	}

	public void close() {
		try {
			connection.close();
		} catch (SQLException ignored) { }
	}
}
